import { to } from 'await-to-js';
import { getToken, removeToken, setToken } from '@/utils/auth';
import { login as loginApi, logout as logoutApi, getInfo as getUserInfo } from '@/api/login';
import type { LoginData } from '@/api/types';
import defAva from '@/assets/images/profile.jpg';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getUserProfile } from '@/api/system/user';

export const useUserStore = defineStore('user', () => {
  const token = ref(getToken());
  const name = ref('');
  const username = ref('');
  const nickname = ref('');
  const userId = ref<string | number>('');
  const tenantId = ref<string>('');
  const avatar = ref('');
  const deptname = ref('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const permissions = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const departmentId = ref<number>();
  const postGroup = ref<string>('');
  /**
   * 登录
   * @param userInfo
   * @returns
   */
  const login = async (userInfo: LoginData): Promise<void> => {
    try {
      console.log('开始登录，用户信息:', userInfo);

      const [err, res] = await to(loginApi(userInfo));
      console.log('登录API响应:', { err, res });

      if (res) {
        const data = res.data;
        console.log('登录成功，响应数据:', data);

        if (data && data.access_token) {
          setToken(data.access_token);
          token.value = data.access_token;
          console.log('Token已设置:', data.access_token.substring(0, 20) + '...');
          return Promise.resolve();
        } else {
          console.error('登录响应中没有access_token:', data);
          return Promise.reject(new Error('登录响应格式错误'));
        }
      }

      console.error('登录失败:', err);
      return Promise.reject(err);
    } catch (error) {
      console.error('登录过程中发生错误:', error);
      return Promise.reject(error);
    }
  };

  // 获取用户信息
  const getInfo = async (): Promise<void> => {
    try {
      console.log('开始获取用户信息...');

      const [err, res] = await to(getUserInfo());
      const userprofile = await getUserProfile();
      console.log('用户信息API响应:', { err, res });

      if (res) {
        const data = res.data;
        console.log('用户信息数据:', data);

        if (!data || !data.user) {
          console.error('用户信息响应格式错误:', data);
          return Promise.reject(new Error('用户信息响应格式错误'));
        }

        const user = data.user;
        const profile = user.avatar == '' || user.avatar == null ? defAva : user.avatar;

        // 安全处理角色和权限数据
        try {
          console.log('处理角色权限数据:', { roles: data.roles, permissions: data.permissions });

          if (data.roles && Array.isArray(data.roles) && data.roles.length > 0) {
            // 确保 roles 是字符串数组
            roles.value = data.roles.filter(role => typeof role === 'string');
            console.log('过滤后的角色:', roles.value);

            // 确保 permissions 是字符串数组
            if (data.permissions && Array.isArray(data.permissions)) {
              permissions.value = data.permissions.filter(perm => typeof perm === 'string');
              console.log('过滤后的权限:', permissions.value);
            } else {
              permissions.value = [];
              console.log('权限数据无效，设置为空数组');
            }
          } else {
            roles.value = ['ROLE_DEFAULT'];
            permissions.value = [];
            console.log('角色数据无效，使用默认角色');
          }

          console.log('最终用户角色:', roles.value);
          console.log('最终用户权限:', permissions.value);
        } catch (roleError) {
          console.error('处理角色权限数据时出错:', roleError);
          roles.value = ['ROLE_DEFAULT'];
          permissions.value = [];
        }

        // 设置用户基本信息
        name.value = user.userName || '';
        username.value = user.userName || '';
        nickname.value = user.nickName || '';
        deptname.value = user.deptName || '';
        departmentId.value = user.deptId;
        avatar.value = profile;
        userId.value = user.userId || '';
        tenantId.value = user.tenantId || '';
        postGroup.value = userprofile.data.postGroup;
        console.log('用户信息设置完成:', {
          name: name.value,
          username: username.value,
          roles: roles.value,
          permissions: permissions.value
        });

        return Promise.resolve();
      }

      console.error('获取用户信息失败:', err);
      return Promise.reject(err);
    } catch (error) {
      console.error('获取用户信息过程中发生错误:', error);
      return Promise.reject(error);
    }
  };

  // 注销
  const logout = async (): Promise<void> => {
    await logoutApi();
    token.value = '';
    roles.value = [];
    permissions.value = [];
    removeToken();
  };

  const setAvatar = (value: string) => {
    avatar.value = value;
  };

  return {
    userId,
    tenantId,
    token,
    nickname,
    avatar,
    roles,
    permissions,
    deptname,
    departmentId,
    username,
    postGroup,
    login,
    getInfo,
    logout,
    setAvatar
  };
});
